package com.lyl.mallcloud.controller;

/**
 * @Author: Liyunlong
 * @Date: 2024/05/10/19:25
 * @Description:
 */

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.UUID;
import com.lyl.mallcloud.pojo.Admin;
import com.lyl.mallcloud.service.IAdminService;
import com.lyl.mallcloud.utils.Md5Util;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
public class UserController {

    @Autowired
    private IAdminService adminService;
    private LineCaptcha lineCaptcha;
    @Value("${auth.code}")
    private String AUTH_CODE;
    @Autowired
    RedisTemplate redisTemplate;
    private static final String USER_ONLINE = "user:oline";

    @GetMapping("/")
    public String showLoginForm() {
        return "login";
    }

    @GetMapping("/register")
    public String showRegisterForm() {
        return "Register";
    }

    /***
     * @Description: 管理员注册
     * @Author: Liyunlong
     * @Date: 2024/5/11
     */
    @RequestMapping(value = "/register")
    public String register(HttpServletRequest request, HttpSession session, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String safeCode = request.getParameter("safeCode");
        if (username.equals("") || password.equals("")) {
            return "Register";
        }
        Admin admin = adminService.findByUsername(username);
        if (admin != null) {
            model.addAttribute("msg", "用户名已存在");
            return "Register";
        }
        if (safeCode.equals(AUTH_CODE)) {
            String salt = UUID.randomUUID(true).toString();
            password = Md5Util.getMD5String(password + salt);
            Admin admin2 = new Admin();
            admin2.setUsername(username);
            admin2.setPassword(password);
            admin2.setSalt(salt);
            adminService.save(admin2);
        }
        model.addAttribute("msg", "注册成功");
        log.info("管理员注册成功：{}", username);
        return "login";
    }

    /***
     * @Description: 登录的逻辑 Shiro框架
     * @Author: Liyunlong
     * @Date: 2024/5/11
     */
    @RequestMapping(value = "/login")
    public String index(HttpServletRequest request, HttpSession session, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String imgText = request.getParameter("safeCode");

        try {
            if (imgText == null || (!imgText.equals(lineCaptcha.getCode()))) {
                log.info("验证码错误");
                return "redirect:/";
            }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);

            String username1 = usernamePasswordToken.getUsername();
            model.addAttribute("username", username1);
            session.setAttribute("userName", username);
            Admin byUsername = adminService.findByUsername(username);
            Integer id = byUsername.getId();
            redisTemplate.opsForSet().add(USER_ONLINE, id);
            redisTemplate.expire(USER_ONLINE, 30, TimeUnit.MINUTES);
            log.info("登录成功");
            return "redirect:/product/DataView";
        } catch (UnknownAccountException uae) {
            log.info("用户不存在");
            return "redirect:/login";
            // 处理账户不存在的情况
        } catch (IncorrectCredentialsException ice) {
            log.info("密码错误");
            // 处理密码不匹配的情况
            return "redirect:/login";
        } catch (AuthenticationException ae) {
            // 其他未处理的认证异常
            return "redirect:/login";
        }
    }

    /***
     * @Description:
     * @Author: Liyunlong
     * @Date: 2024/5/11
     */

    @RequestMapping("/user/Info")
    public String userInfo(HttpSession session) {
        String username = (String) session.getAttribute("userName");
        session.setAttribute("userName", username);
        if (username != null) {
            return "user/Info";
        } else {
            return "redirect:/login";
        }
    }

    /***
     * @Description: 验证码
     * @Author: Liyunlong
     * @Date: 2024/5/11
     */
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 5);
        // 定义图片的显示大小
        lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            lineCaptcha.setGenerator(randomGenerator);
            lineCaptcha.write(response.getOutputStream());
            log.info("生成的验证码:{}", lineCaptcha.getCode());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * @Description: 管理员个人中心
     * @Author: Liyunlong
     * @Date: 2024/5/11
     */
    @GetMapping("/adminInfo")
    public String info(@RequestParam(value = "name") String name, Model model, HttpSession session) {
        Admin admin = adminService.findByUsername(name);
        model.addAttribute("user", admin);
        return "/user/Info";
    }

}



